//
//  VideoView.m
//  SYiDaiy
//
//  Created by dllo on 16/9/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VideoView.h"

@implementation VideoView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _backgroudView = [[UIView alloc] initWithFrame:self.bounds];
        _backgroudView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_backgroudView];


        _videoTopImageView = [UIImageView new];
        [_backgroudView addSubview:_videoTopImageView];
        _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playButton addTarget:self action:@selector(playButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [_backgroudView addSubview:_playButton];
        
        _slider = [[UISlider alloc] init];
        _slider.minimumValue = 100;
        _slider.maximumValue = 200;
        
        [self addSubview:_slider];

        
    }
    return self;
}

- (void)sliderClicked
{
    CMTimeValue value = _player.currentItem.duration.value;
    CMTimeScale scale = _player.currentItem.duration.timescale;
    
    _sumPlayOperation =  value / scale;
    CMTime tm = CMTimeMakeWithSeconds(_slider.value * _sumPlayOperation, scale);
   
    [_player seekToTime:tm completionHandler:^(BOOL finished) {
        [self.player play];
    }];


}

- (void)initWithURL:(NSURL *)url
{
   
       [_slider addTarget:self action:@selector(sliderClicked) forControlEvents:UIControlEventTouchUpInside];
    //创建一个playerItem,视频项目对象
        self.playerItem = [[AVPlayerItem alloc]initWithURL:url];
        //创建播放器player对象
        self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
        //创建用来承载播放器播放的layer对象
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        //设置播放时候的尺寸
        self.playerLayer.frame = self.bounds;
        //设置视频填充的方式
        self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//        将播放器添加到背景view的layer层上
    
        [_backgroudView.layer insertSublayer:self.playerLayer atIndex:0];

}



- (void)layoutSubviews
{
    _playButton.frame = CGRectMake(100, 100, 50, 50);
    _videoTopImageView.frame = CGRectMake(10, 10, 355, 180);
    _slider.frame = CGRectMake(90, 170, 200, 10);
}
@end
